package com.bigfans.catalogservice.service.attribute;

import com.bigfans.catalogservice.dao.AttributeOptionDAO;
import com.bigfans.catalogservice.model.AttributeOption;
import com.bigfans.catalogservice.model.AttributeValue;
import com.bigfans.catalogservice.service.category.CategoryService;
import com.bigfans.framework.dao.BaseServiceImpl;
import com.bigfans.framework.event.ApplicationEventBus;
import com.bigfans.framework.utils.BeanUtils;
import com.bigfans.framework.utils.CollectionUtils;
import com.bigfans.model.event.attribute.AttributeCreatedEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @Title:
 * @Description:
 * @author lichong
 * @date 2015年10月7日 上午11:52:42
 * @version V1.0
 */
@Service(AttributeOptionServiceImpl.BEAN_NAME)
public class AttributeOptionServiceImpl extends BaseServiceImpl<AttributeOption> implements
		AttributeOptionService {
	
	public static final String BEAN_NAME = "attributeOptionService";
	
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private AttributeValueService attributeValueService;
	@Autowired
	private ApplicationEventBus eventBus;
	
	private AttributeOptionDAO attributeOptionDAO;
	
	@Autowired
	public AttributeOptionServiceImpl(AttributeOptionDAO attributeOptionDAO) {
		super(attributeOptionDAO);
		this.attributeOptionDAO = attributeOptionDAO;
	}
	
	@Override
	@Transactional
	public void create(AttributeOption e) throws Exception {
		super.create(e);
		// 单独保存属性值到属性值表
		List<String> values = e.getValues();
		if(CollectionUtils.isNotEmpty(values)){
			List<AttributeValue> valueList = new ArrayList<AttributeValue>();
			for(String val : values){
				AttributeValue av = new AttributeValue();
				av.setValue(val);
				av.setOptionId(e.getId());
				av.setCategoryId(e.getCategoryId());
				valueList.add(av);
			}
			attributeValueService.batchCreate(valueList);
		}
		AttributeCreatedEvent event = new AttributeCreatedEvent();
		BeanUtils.copyProperties(e , event);
		eventBus.publishEvent(event);
	}
	
	@Override
	@Transactional(readOnly=true)
	public List<AttributeOption> listByCategory(String catId) throws Exception {
		List<String> parentIds = categoryService.listParentIds(catId);
		parentIds.add(catId);
		List<AttributeOption> attrOptions = attributeOptionDAO.listByCategory(parentIds);
		for (AttributeOption item : attrOptions) {
			if(item.getInputType().equals(AttributeOption.INPUTTYPE_SELECT)){
				List<AttributeValue> valueList = attributeValueService.listByOptionId(item.getId());
				item.setValueList(valueList);
			}
		}
		return attrOptions;
	}

	@Override
	@Transactional(readOnly=true)
	public List<AttributeOption> listByCategory(List<String> categoryIds) throws Exception {
		return attributeOptionDAO.listByCategory(categoryIds);
	}
}
